package DP;

public class FindLength {
    public static void main(String[] args) {
        int[] nums1 = new int[]{1, 2, 3, 2, 8};
        int[] nums2 = new int[]{5, 6, 1, 4, 7};
        System.out.println(findLength(nums1, nums2));
    }

    public static int findLength(int[] nums1, int[] nums2) {
        if (nums1.length == 0 || nums2.length == 0) {
            return 0;
        }
        int result = 0;
        int dp[][] = new int[nums2.length][nums1.length];
        for (int i = 0; i < nums1.length; i++) {
            if (nums1[i] == nums2[0]) {
                dp[0][i] = 1;
            }
        }
        for (int i = 0; i < nums2.length; i++) {
            if (nums1[0] == nums2[i]) {
                dp[i][0] = 1;
                result = 1;
            }
        }

        for (int i = 0; i < nums1.length; i++) {
            for (int j = 0; j < nums2.length; j++) {
//                System.out.print(dp[i][j]);
            }
//            System.out.println();
        }

        for (int i = 1; i < nums1.length; i++) {
            for (int j = 1; j < nums2.length; j++) {
                if (nums1[i] == nums2[j]) {
                    dp[j][i] = dp[j - 1][i - 1] + 1;
                    result = Math.max(result, dp[j][i]);
                }
//                System.out.print(dp[i][j]);
            }
//            System.out.println();
        }

//        for (int i = 0; i < nums1.length; i++) {
//            for (int j = 0; j < nums2.length; j++) {
//                System.out.print(dp[i][j]);
//            }
//            System.out.println();
//        }

        return result;
    }
}
